﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Threading;

namespace AL
{
    public class AsynWebRequest
    {
        public Uri Url { get; set; }
        private WebBrowser _browser;

        public AsynWebRequest(string url)
        {
            this.Url = new Uri(url);
        }

        public void Navigate()
        {
            if (this.Url == null)
                throw new Exception("URL cannot be empty");
            this._browser = new WebBrowser();
            this._browser.ScriptErrorsSuppressed = true;
            this._browser.DocumentCompleted += (s, e) =>
            {
                if (e.Url.Equals(this._browser.Url))
                {
                    var arg = new RequestCompletedEventArgs
                    {
                        Document = this._browser.Document
                    };
                    RequestCompleted(s, arg);
                }
            };
            this._browser.Url = this.Url;
        }
        /// <summary>/// 获取具有指定标识符的节点内容/// </summary>
        /// <param name="identifier">元素的id或name属性</param>
        /// <returns></returns>
        public string this[string identifier]
        {
            get
            {
                if (this.RequestCompleted == null)
                {
                    throw new Exception("The document has not been completely loaded");
                }
                return this._browser.Document.GetElementById(identifier).InnerText;
            }
        }
        public delegate void RequestCompletedEventHandler(object sender, RequestCompletedEventArgs e);
        public event RequestCompletedEventHandler RequestCompleted;
        public class RequestCompletedEventArgs
        {
            public HtmlDocument Document { get; set; }
        }

        //[STAThread]
        //static void Main(string[] args)
        //{
        //    var awr = new AsynWebRequest("http://stockhtm.finance.qq.com/sstock/ggcx/300101.shtml");
        //    awr.RequestCompleted += (s, a) =>
        //    {
        //        MessageBox.Show(a.Document.GetElementById("main-4").InnerText); MessageBox.Show(awr["main-4"]);
        //    };
        //    awr.Navigate();
        //}
    }
}